<?php
namespace App\Http\Controllers\Api\Tg;

use Carbon\Carbon;

use App\Models\Bill\Bill;

use App\Models\Bill\BillGoods;

use App\Models\Mall\MallMaster;

use App\Models\Tg\Tg;  //团购维护主表

use App\Models\ConfigureFunction; //功能配置表

use App\Models\Wx\WxCustomer;  //微信会员表

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\Customer\Customer;

use App\Models\Deliver\Deliver;

use App\Service\WdhService;

use App\Models\Pay\SysPaytype;

use App\Service\Checkout\TgCheckoutService;

class TgCheckoutController extends Controller
{
    private $tuan_bill_data;

    private $config_array;

    private $activity_mall = array();

    //购物车数组
    private $bill_array;

    /**
     * 1. 获取结算配置信息
     * $type 1、结算  2、支付
     * @return array
     */
    public function getConfig($tuan_id = 0) {

        if ( !ebsig_is_int($tuan_id) ) {
            $tuan_id = $this->tuan_bill_data['tuan_id'];
        }

        $tuan_data = Tg::getCache($tuan_id);
        if ( !$tuan_data ) {
            return [];
        }

        $this->activity_mall = $tuan_data['activity_mall'];

        $config_array = $tuan_data['config'];
        if (!$config_array)
            return [];

        $this->config_array = $config_array;
        return $config_array;

    }


    /**
     * 结算
     * @param Request $req
     * @param Response $res
     * @return mixed
     */
    private function checkBill($pcustID, $data = null)
    {

        //实例化团购结算类
        $tg_checkout_service = new TgCheckoutService();

        $result = $tg_checkout_service->checkout($this->tuan_bill_data);
        if ( $result['code'] != 200 ) {
            return array(
                'code' => 400,
                'message' => $result['message']
            );
        }

        $return_array['checkout'] = $result['data'][1];
        
        if ( $data ) {
            $return_array = array_merge($return_array, $data);
        }

        Redis::setex('TUAN_BILL_DATA_' . $pcustID, 360000, json_encode($result['data'][0], true));

        return array(
            'code' => 200,
            'message' => 'ok',
            'data' => $return_array
        );

    }

    /**
     * 初始化拼团结算页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $bill_no = $request->input('bill_no', 0); //参团主订单号
        $mallID = $request->input('mallID', 1); //门店ID

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        $check_data = [
            'config_id' => 0,
            'is_send' => 0,
            'cust_deliver_id' => 0,
            'zt_mobile' => 0,
            'zt_cust_name' => 0,
            'send_limit_money' => 0,
            'is_zt_time' => 0,
            'is_send_time' => 0,
            'is_use_balance' => 0,
            'is_use_points' => 0,
            'is_tuan' => 0,
            'is_mall' => 0,
            'parent_bill_no' => $bill_no,
            'send_type' => [
                '1' => [
                    'name' => '送货上门',
                    'selected' => 0
                ],
                '2' => [
                    'name' => '门店自提',
                    'selected' => 1
                ]
            ]
        ];

        //获取团购订单信息
        $tg_order = json_decode(Redis::get('TUAN_BILL_DATA_' . $pcustID), true);
        if (!$tg_order) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
        }
        $tuan_id = $tg_order['tuan_id'];


        //获取团购信息
        $tg = Tg::getCache($tuan_id);
        if (!$tg) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
        }


        //查询会员信息
        $customer = Customer::select('pcustID', 'custID', 'cardNo')->find($pcustID);
        if (!$customer) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
        }

        //查询微信公众号粉丝信息，用于查询会员账户余额和积分
        $wechat_customer = WxCustomer::where(['pcustID'=> $pcustID])->first();
        if ($wechat_customer) {
            $openId = $wechat_customer->openId;
        } else {
            $openId = '';
        }

        //实例化团购结算类
        $tg_checkout_service = new TgCheckoutService();

        /**
         * 微信支付方式类型  1、普通版 2、代理版
         */

        $check_data['wechat_pay_type'] = ConfigureFunction::getConfigureField(9, 'wechat_pay_type');

        /**
         * ===============================================
         * 获取结算配置
         * ===============================================
         */
        $checkout_config = $tg['config'];
        if (!$checkout_config) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
        }
        $check_data['config_id'] = $checkout_config['config_id'];


        /**
         * ====================================
         * 配送方式
         * ====================================
         */
        $send_type_data = explode(',', $checkout_config['send_type']);
        foreach ( $check_data['send_type'] as $key=>$item ) {
            if ( !in_array($key, $send_type_data) ) {
                unset($check_data['send_type'][$key]);
            }
        }

        /**
         * ==========================================
         * 选店
         * ==========================================
         */
        $deliver_id = 0;
        $check_data['is_select_mall'] = 0;
        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');

        if ($is_open_choose_mall == 1) { //选店模式

            $check_data['is_select_mall'] = 1;

            //判断是否有选择门店
            if (!ebsig_is_int($mallID)) {
                return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
            }

            //查询门店信息
            $mall = MallMaster::getCache($mallID);
            if (!$mall) {
                return response()->json(['code' => 100003, 'message' => '门店不存在']);
            }

            //判断自提支持
            if (isset($mall['mention']) && $mall['mention'] == 0) {
                unset($checkout_config['send_type']['2']);
            }

            //判断配送支持
            if (isset($mall['mall_is_send']) && $mall['mall_is_send'] == 0) {
                unset($checkout_config['send_type']['1']);
            }

            $check_data['send_limit_money'] = $mall['send_limit_money'];

            $zt_id = 0;
            $zt_name = '';
            $zt_code = '';
            $mallName = $mall['mallName'];
            $mallCode = $mall['mallCode'];
            if ($mall['mallType'] == 2) {
                $zt_id = $mall['mallID'];
                $zt_name = $mall['mallName'];
                $zt_code = $mall['mallCode'];
            }

            //查询会员地址信息
            $deliver = Deliver::where(['pcustID' => $pcustID, 'mallID' => $mallID, 'zt_id' => $zt_id])->first();
            if (!$deliver) {

                $deliver_id = generate_seqno('seqno_custdeliver', true);
                $deliver = new Deliver();
                $deliver->uuid = makeUuid();
                $deliver->timeStamp = Carbon::now();
                $deliver->creator = 'system';
                $deliver->createTime = Carbon::now();
                $deliver->deliverID = $deliver_id;
                $deliver->pcustID = $pcustID;
                $deliver->provinceName = $mall['provinceName'];
                $deliver->cityName = $mall['cityName'];
                $deliver->countyName = $mall['countyName'];
                $deliver->provinceid = $mall['provinceid'];
                $deliver->cityid = $mall['cityid'];
                $deliver->countyid = $mall['countyid'];
                $deliver->address = $mall['address'];
                $deliver->custname = isset($customer->custname) ? $customer->custname : '';
                $deliver->postalCode = '';
                $deliver->mobile = $mall['mobile'];
                $deliver->phone = $mall['phone'];
                $deliver->mallID = $mallID;
                $deliver->mallName = $mallName;
                $deliver->mallCode = $mallCode;
                $deliver->is_default = 0;
                $deliver->zt_name = $zt_name;
                $deliver->zt_code = $zt_code;
                $deliver->save();
            } else {
                $deliver_id = $deliver->deliverID;
            }

        }

        if ( count($check_data['send_type']) == 1 ) {
            if ( isset($check_data['send_type']['1']) ) {
                $check_data['send_type']['1']['selected'] = 1;
                $tg_order['ziti'] = 0;
            }
            if ( isset($check_data['send_type']['2']) ) {
                $check_data['send_type']['2']['selected'] = 1;
                $tg_order['ziti'] = 1;
            }
        }


        /**
         * ===============================================
         * 生成默认地址信息
         * ===============================================
         */
        if (in_array(1, $send_type_data)) {
            $res = $tg_checkout_service->getAddress($tg_order, 0, $deliver_id, $pcustID);
            $check_data['deliver'] = $res[0];
            $tg_order = $res[1];
        }


        /**
         * ===============================================
         * 生成默认门店信息
         * ===============================================
         */
        if (in_array(2, $send_type_data)) {
            $res = $tg_checkout_service->getAddress($tg_order, 1, $deliver_id, $pcustID, $tg['activity_mall'], $mallID);
            $check_data['mall'] = $res[0];
            $tg_order = $res[1];
        }


        /**
         * ===============================================
         * 提货时间
         * ===============================================
         */
        $check_data['ziti_time'] = $tg_checkout_service->order_time_func(13);
        if ( !empty($check_data['ziti_time']) ) {
            $check_data['is_zt_time'] = 1;
        }


        /**
         * ===============================================
         * 配送时间
         * ===============================================
         */
        $check_data['send_time'] = $tg_checkout_service->order_time_func(12);
        if ( !empty($check_data['send_time']) ) {
            $send_time_type = 1;
            foreach($check_data['send_time'] as $t) {
                if (!isset($t['id']))
                    $send_time_type = 2;
            }
            $check_data['send_time'] = [
                'send_time_type' => $send_time_type,
                'send_time_list' => $check_data['send_time']
            ];
            $check_data['is_send_time'] = 1;
        }

        /**
         * ===============================================
         * 提货条件
         * ===============================================
         */
        $pick_up_goods_conditions = explode(',', $checkout_config['pick_up_goods_conditions']);
        if (in_array(1, $pick_up_goods_conditions)) {
            $check_data['zt_mobile'] = 1;
        }
        if (in_array(3, $pick_up_goods_conditions)) {
            $check_data['zt_cust_name'] = 1;
        }

        //获取提货人姓名和提货人手机号信息
        $cust_ziti_info_json = Redis::get('CUST_ZITI_INFO_' . $pcustID);
        if ( $cust_ziti_info_json ) {
            $cust_ziti_info = json_decode($cust_ziti_info_json, true);
            if ( $cust_ziti_info ) {
                $check_data['cust_mobile'] = isset($cust_ziti_info['cust_mobile']) ? $cust_ziti_info['cust_mobile'] : '';
                $check_data['cust_name'] = isset($cust_ziti_info['cust_name']) ? $cust_ziti_info['cust_name'] : '';
            }
        }

        
        /**
         * ===============================================
         * 商品
         * ===============================================
         */
        $check_data['goods'] = [
            'goodsName' => $tg_order['goods'][0]['goodsName'],
            'one_level_spec_str' => $tg_order['goods'][0]['one_level_spec_str'],
            'two_level_spec_str' => $tg_order['goods'][0]['two_level_spec_str'],
            'goods_amount' => $tg_order['goods'][0]['goods_amount'],
            'pic' => $tg_order['goods'][0]['pic'],
            'price' => $tg_order['goods'][0]['price']
        ];

        /**
         * ===============================================
         * 支付方式
         * ===============================================
         */
        $check_data['pay_type'] = $tg_checkout_service->getPayType($checkout_config['pay_type']);
        if ( in_array(2, explode(',', $checkout_config['pay_type'])) ) {
            $check_data['is_use_balance'] = 1;
        }
        if ( in_array(3, explode(',', $checkout_config['pay_type'])) ) {
            $check_data['is_use_points'] = 1;
        }

        /**
         * ===============================================
         * 会员余额
         * ===============================================
         */
        $check_data['balance'] = 0;
        if ( $check_data['is_use_balance'] == 1 ) {
            $args_data = array(
                'pcustID' => $pcustID,
                'cardNo'  => $customer->cardNo
            );
            $check_data['balance'] = WdhService::balance( $args_data );
        }

        /**
         * ===============================================
         * 会员积分
         * ===============================================
         */
        $check_data['exchange_rate'] = $exchange_rate = ConfigureFunction::getConfigureField(2, 'points_exchange_ratio', 100);;
        $check_data['points'] = 0;
        $check_data['points_cash'] = 0;
        if ( $check_data['is_use_points'] == 1 ) {
            $args_data = array(
                'pcustID' => $pcustID,
                'openId'  => $openId,
                'cardNo'  => $customer->cardNo
            );
            $points = WdhService::points( $args_data );
            $check_data['points'] = $points;
            $check_data['points_cash'] = 0;
            if ( $points > 0 ) {
                $check_data['points_cash'] = floor(($points / $exchange_rate) * 100) / 100;
            }
        }

        /**
         * ===============================================
         * 结算信息
         * ===============================================
         */
        $res = $tg_checkout_service->checkout($tg_order);
        if ($res['code'] != 200) {
            return response()->json(['code' => $res['code'], 'message' => $res['message']]);
        }
        $tg_order = $res['data'][0];
        $check_data['checkout'] = $res['data'][1];


        Redis::setex('TUAN_BILL_DATA_' .  $pcustID, 360000, json_encode($tg_order, true));

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data]);

    }


    /**
     * 选择收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function chooseAddress(Request $request)
    {

        $deliverID = $request->input('deliverID');
        $sendTypeID = $request->input('sendTypeID');
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');
        $session_id = $request->input('session_id', session_id());
        $mallID = $request->input('mallID');
        $platform = $request->input('platform', 6);

        //实例化团购结算类
        $tg_checkout_service = new TgCheckoutService();

        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        if (!ebsig_is_int($deliverID, 2)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：deliverID']);
        }

        //获取购物车信息
        $this->tuan_bill_data = json_decode(Redis::get('TUAN_BILL_DATA_' . $pcustID), true);
        if (!$this->tuan_bill_data) {
            return response()->json(['code' => 400, 'message' => '暂无订单信息']);
        }

        //配送方式
        if (isset($sendTypeID) && ebsig_is_int($sendTypeID)) {
            $send_data = $tg_checkout_service->getSend($this->tuan_bill_data, $sendTypeID);
            if($send_data){
                $this->tuan_bill_data = $send_data[1];
            }
        }

        //查询会员收货地址
        $deliver_data = $tg_checkout_service->getDeliver( $this->tuan_bill_data, $pcustID, $deliverID );
        if (!$deliver_data) {
            return response()->json(['code' => 400, 'message' => '收货地址信息没有找到，请选择其他收货地址']);
        }

        $mall_config = ConfigureFunction::getConfigure(8);
        if (isset($mall_config['is_open_choose_mall']) && $mall_config['is_open_choose_mall'] == 1) {

            if ( !ebsig_is_int($mallID) ) {
                return response()->json(['code' => 400, 'message' => '请先绑定门店']);
            }
            /**
             * ===========start检查门店配送范围==============
             */
            $result_array = WdhService::checktrictSendRange(array('mallID' => $mallID, 'longitude' => $longitude, 'latitude' => $latitude));
            if ($result_array['code'] != 200) {
                return response()->json(['code' => $result_array['code'], 'message' => $result_array['message']]);
            }

            /**
             * ===========end检查门店配送范围==============
             */

        }


        $this->tuan_bill_data = $deliver_data[1];
        $return_array['deliver'] = $deliver_data[0];

        //计算价格
        $return_array = $this->checkBill($pcustID, $return_array['deliver']);

        if ( $return_array['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $return_array['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_array['data']]);
    }

    /**
     * 使用积分
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function usePoints(Request $request)
    {

        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        $use_points = $request->input('use_points');//使用积分

        //获取购物车信息
        $this->tuan_bill_data = json_decode(Redis::get('TUAN_BILL_DATA_' . $pcustID), true);

        if($this->tuan_bill_data['bill_payable'] <= 0){
            return response()->json(['code' => 400, 'message' => '订单已付款']);
        }

        //查询会员信息
        $cust_info = Customer::where(['pcustID'=> $pcustID])->first();
        if (!$cust_info) {
            return response()->json(['code' => 400, 'message' => '会员信息不存在']);
        }
        $cust_info = $cust_info->toArray();

        $custPointsSet = ConfigureFunction::getConfigure(2);

        $exchange_rate = 100;
        $max_rate = 100;
        if (isset($custPointsSet['points_exchange_ratio'])) {
            $exchange_rate = $custPointsSet['points_exchange_ratio'];
        }
        if (isset($custPointsSet['points_payable_ration'])) {
            $max_rate = $custPointsSet['points_payable_ration'];
        }

        //查询可用积分
        $args_array = array(
            'pcustID' => $pcustID,
            'cardNo' => $cust_info['cardNo']
        );
        $points = WdhService::points( $args_array );

        if (!empty($use_points)) {
            if ( !ebsig_is_int($use_points) ) {
                return response()->json(['code' => 400, 'message' => '请输入积分数']);
            } else if ($points < $use_points) {
                return response()->json(['code' => 400, 'message' => '没有足够的积分可用']);
            }
            $points = $use_points;
        }

        $bill_payable_points = $this->tuan_bill_data['bill_payable'] * $exchange_rate;
        if ( $bill_payable_points < $points ) {
            $points = $this->tuan_bill_data['bill_payable'] * $exchange_rate;
        }

        $points = $bill_payable_points * ($max_rate/100) < $points ? $bill_payable_points * ($max_rate/100) : $points;

        //记录积分使用信息
        $this->tuan_bill_data['use_points'] = array(
            'points' => $points,
            'points_cash' => $points > 0 ? floor(($points / $exchange_rate) * 100) / 100 : 0
        );

        //计算价格
        $check_data = $this->checkBill($pcustID);
        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);

    }

    /**
     * 使用余额
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function useBalance(Request $request)
    {

        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        //获取购物车信息
        $this->tuan_bill_data = json_decode(Redis::get('TUAN_BILL_DATA_' . $pcustID), true);
        if($this->tuan_bill_data['bill_payable'] <= 0){
            return response()->json(['code' => 400, 'message' => '订单已付款']);
        }

        //查询会员信息
        $cust_info = Customer::where(['pcustID'=> $pcustID])->first();
        if (!$cust_info) {
            return response()->json(['code' => 400, 'message' => '会员信息不存在']);
        }
        $cust_info = $cust_info->toArray();

        //查询可用余额
        $args_array = array(
            'pcustID' => $pcustID,
            'cardNo' => $cust_info['cardNo']
        );
        $balance = WdhService::balance($args_array);

        //当余额大于付款金额
        if ($this->tuan_bill_data['bill_payable'] < $balance) {
            $balance = $this->tuan_bill_data['bill_payable'];
        }

        //保存余额使用信息
        $this->tuan_bill_data['use_balance'] = array(
            'deduct_amount' => $balance
        );

        //计算价格
        $check_data = $this->checkBill($pcustID);

        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);

    }

    /**
     * 取消使用积分
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function cancelUsePoints(Request $request)
    {
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        //获取购物车信息
        $this->tuan_bill_data = json_decode(Redis::get('TUAN_BILL_DATA_' . $pcustID), true);

        if(isset($this->tuan_bill_data['use_points'])){
            unset($this->tuan_bill_data['use_points']);
        }

        $check_data = $this->checkBill($pcustID);

        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);
    }

    /**
     * 取消使用余额
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function cancelUseBalance(Request $request)
    {
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        //获取购物车信息
        $this->tuan_bill_data = json_decode(Redis::get('TUAN_BILL_DATA_' . $pcustID), true);

        if(isset($this->tuan_bill_data['use_balance'])){
            unset($this->tuan_bill_data['use_balance']);
        }

        $check_data = $this->checkBill($pcustID);

        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);
    }

    /**
     * 验证支付密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function checkPayPwd(Request $request)
    {
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        $req_data = $request->all();

        if ( !isset($req_data['pwd']) || empty($req_data['pwd']) ) {
            return response()->json(['code' => 400, 'message' => '请输入支付密码']);
        }

        //获取会员信息
        $cust_base_info = Customer::where(['pcustID' => $pcustID])->first();
        if( empty($cust_base_info) ){
            return response()->json(['code' => 400, 'message' => '没有找到会员信息']);
        }
        $cust_base_info = $cust_base_info->toArray();

        $args_array = array(
            'pcustID' => $pcustID,
            'pwd' => $req_data['pwd'],
            'cardNo' => $cust_base_info['cardNo']
        );

        //调取接口验证支付密码
        $result_array = WdhService::checkPwd($args_array);
        if ( $result_array['code'] != 200 ) {
            return response()->json(['code' => $result_array['code'], 'message' => $result_array['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok']);

    }

    /*
     * 订单支付详情
     */
    public function tuanPay( Request $request )
    {

        $host = $request->getSchemeAndHttpHost();
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }

        $bill_no = $request->input('bill_no');
        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 10001, 'message' => '请登录']);
        }
        if ( !$bill_no ) {
            return response()->json(['code' => 10002, 'message' => '缺少参数：bill_no']);
        }

        //主订单信息
        $bill_master = Bill::where(['bill_no' => $bill_no ,'pcustID' => $pcustID])->first();
        if ( !$bill_master ) {
            return response()->json(['code' => 10003, 'message' => '订单不存在']);
        } else {
            $bill_master = $bill_master->toArray();
        }

        if ( $bill_master['pay_status'] == 1 ) {
            return response()->json(['code' => 10004, 'message' => '订单已支付']);
        }

        //返回的数据
        $data = [
            'parent_bill_no' => $bill_master['parent_bill_no']
        ];

        //订单商品
        $bill_goods = BillGoods::where( 'bill_no' , $bill_no )->first();
        if ( !$bill_goods ) {
            return response()->json(['code' => 10005, 'message' => '订单商品数据没有找到']);
        } else {
            $bill_goods = $bill_goods->toArray();
        }

        $tuan_data = Tg::getCache($bill_master['activity_id']);
        if ( !$tuan_data ) {
            return response()->json(['code' => 10006, 'message' => '团购信息不存在']);
        }

        //团购结算配置
        $config_data = $tuan_data['config'];
        $goods_array = array();

        /**
         * ===============================================
         * 商品
         * ===============================================
         */
        if ( $tuan_data['goods'] ) {
            foreach ($tuan_data['goods'] as $item) {
                if ( $bill_goods['goods_postID'] == $item['postID'] ) {
                    $goods_array = $item;
                    break;
                }
            }
        }

        if ( !empty($goods_array) ) {
            $data['goods'] = array(
                'goodsName' => $bill_goods['goods_name'],
                'one_level_spec_str' => $goods_array['one_level_spec_str'],
                'two_level_spec_str' => $goods_array['two_level_spec_str'],
                'goods_amount' => $bill_goods['goods_amount'],
                'pic' => $goods_array['img_link'],
                'price' => $bill_goods['goods_purchasePrice']
            );
        }

        /**
         * ===============================================
         * 自提门店信息、收货地址信息、提货时间、配送时间
         * ===============================================
         */
        //配送方式
        $send_type_array = explode(',', $config_data['send_type']);

        if ( $bill_master['ziti'] == 1 ) {
            $data['send_type']['2']['selected'] = 1;
            $data['mall'] = array(
                'mallName' => $bill_master['mallName'],
                'provinceName' => $bill_master['deliver_province'],
                'cityName' => $bill_master['deliver_city'],
                'countyName' => $bill_master['deliver_county'],
                'address' => $bill_master['deliver_address']
            );

            $ziti_time = ConfigureFunction::getConfigure(13);
            if ( !empty( $ziti_time ) ) {
                $date = date('Y-m-d',strtotime($bill_master['pickup_start_time']));
                $start_time = date('H:i:s',strtotime($bill_master['pickup_start_time']));
                $end_time = date('H:i:s',strtotime($bill_master['pickup_end_time']));
                $data['ziti_time'] = $date . ' ' . $start_time . '-' . $end_time;
            }

        } else {
            $data['send_type']['1']['selected'] = 1;
            $data['deliver'] = array(
                'custName' => $bill_master['deliver_name'],
                'mobile' => $bill_master['deliver_mobile'],
                'provinceName' => $bill_master['deliver_province'],
                'cityName' => $bill_master['deliver_city'],
                'countyName' => $bill_master['deliver_county'],
                'address' => $bill_master['deliver_address']
            );

            $send_time = ConfigureFunction::getConfigure(12);
            if ( !empty( $send_time ) ) {
                if ( !empty($bill_master['send_time']) ) {
                    $data['send_time'] = $bill_master['send_time'];
                } else {
                    $date = date('Y-m-d',strtotime($bill_master['pickup_start_time']));
                    $start_time = date('H:i:s',strtotime($bill_master['pickup_start_time']));
                    $end_time = date('H:i:s',strtotime($bill_master['pickup_end_time']));
                    $data['send_time'] = $date . ' ' . $start_time . '-' . $end_time;
                }
            }
        }

        foreach ( $data['send_type'] as $key=>$item ) {
            if ( !in_array($key, $send_type_array) && $item[$key]['selected'] == 0 ) {
                unset($data['send_type'][$key]);
            }
        }

        /**
         * ===============================================
         * 提货条件
         * ===============================================
         */
        $pick_up_goods_conditions = explode(',', $config_data['pick_up_goods_conditions']);
        if (in_array(1, $pick_up_goods_conditions)) {
            $data['zt_mobile'] = 1;
        }
        if (in_array(3, $pick_up_goods_conditions)) {
            $data['zt_cust_name'] = 1;
        }

        $data['cust_name'] = $bill_master['deliver_name'];
        $data['cust_mobile'] = $bill_master['deliver_mobile'];

        /**
         * ===============================================
         * 支付方式
         * ===============================================
         */
        //查询在线支付方式列表
        $online_data = SysPaytype::where([ 'type' => 2 , 'useFlg' => 1 ])->get()->toArray();
        if ( !empty($online_data) ) {

            foreach($online_data as $online){

                if (!in_array($online['payTypeID'], explode(',', $config_data['pay_type']))) {
                    continue;
                }

                if ( $online['payTypeID'] != 5 ) {
                    continue;
                }

//                if ( $online['payTypeID'] == 4 ) {  //如果是支付宝支付
//                    if ( G_PLATFORM == 1 ) {
//                        continue;
//                    }
//                } else if ( $online['payTypeID'] ==  5) {  //如果是微信支付或易极付微信公账号支付
//                    if (!in_array(G_PLATFORM, array(1, 3, 4, 5))) {
//                        continue;
//                    }
//                    if ( G_PLATFORM == 4 && defined('G_SHOP_SUBSITE') && G_SHOP_SUBSITE == 'wap' ) {
//                        continue;
//                    }
//                }

                $data['pay_type'][] = array(
                    'payTypeID' => $online['payTypeID'],
                    'payTypeName' => $online['payTypeName'],
                    'payment_platform' => $online['payment_platform'],
                    'memo' => $online['memo'],
                    'logo_img' => $host . $online['logo_img']
                );
            }
        }

        /**
         * 微信支付方式类型  1、普通版 2、代理版
         */
        $pay_configure = ConfigureFunction::getConfigure(9);
        $data['wechat_pay_type'] = !empty($pay_configure['wechat_pay_type']) ? $pay_configure['wechat_pay_type'] : 1;

        //会员积分设置
        $custPointsSet = ConfigureFunction::getConfigure(2);
        $exchange_rate = 100;
        if (isset($custPointsSet['points_exchange_ratio'])) {
            $exchange_rate = $custPointsSet['points_exchange_ratio'];
        }
        $data['exchange_rate'] = $exchange_rate;
        $data['checkout']['bill_points_money'] = 0;
        $data['checkout']['bill_balance_money'] = 0;
        if ( $bill_master['bill_points_money'] > 0 ) {
            $data['checkout']['bill_points'] = $bill_master['bill_points_money'] * $exchange_rate;
        }

        if ( $bill_master['bill_balance_money'] > 0 ) {
            $data['checkout']['bill_balance'] = $bill_master['bill_balance_money'];
        }

        $data['checkout']['bill_payable'] = $bill_master['bill_payable'];
        $data['checkout']['deliver_feePaid'] = $bill_master['deliver_feePaid'];


        return response()->json(['code' => 200, 'message' => 'ok' , 'data' => $data ]);

    }
}